import { APP_KEY, APP_SECRET, useAppStore } from '@/stores/app'
import axios from 'axios'
import md5 from 'md5'
import { api } from '.'
import { encode } from 'js-base64'

export const request = axios.create({
  baseURL: '/api',
})

let tokenLoading = null

request.interceptors.request.use(async (config) => {
  if (!config.data) config.data = {}
  if (config.headers['Content-Type'] !== 'multipart/form-data') {
    const appStore = useAppStore()
    if (appStore.token === '') {
      if (!tokenLoading) tokenLoading = api.getToken()
      appStore.token = await tokenLoading
      tokenLoading = null
    }
    config.originData = { ...config.data }
    config.data.token = appStore.token
    if (!config.data.userName) config.data.userName = appStore.accessToken
    config.data.sign = md5(`${APP_KEY}_${APP_SECRET}_${appStore.token}`)
    if (!config.plainText) {
      config.data = encode(JSON.stringify(config.data))
    }
  }
  return config
})

request.interceptors.response.use(
  (response) => {
    response.data.success = response.data.code === 220
    // 如果 code 等于 106 或 103 则重新获取 token 并重新签名后重发请求
    if (response.data.code === 106 || response.data.code === 103) {
      const appStore = useAppStore()
      appStore.token = ''
      return request({ ...response.config, data: response.config.originData })
    }
  
    return response
  },
  (error) => {
    console.error(error);
    return Promise.resolve({
      data: {
        success: false,
        data: null
      }
    })
  }
)
